package edu.buffalo.son.garman;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.Map.Entry;

import edu.buffalo.son.garman.entity.ClaimsRecord;
import edu.buffalo.son.garman.entity.ClaimsRecordIterator;
import edu.buffalo.son.garman.entity.PersonCounts;
import edu.buffalo.son.garman.entity.PersonCounts.IndexAlgorithm;

/**
 * Process all the claims.
 * 
 * @author sravanku
 * 
 */
public final class ClaimsProcessor {

    private static ClaimsProcessor INSTANCE;
    private ClaimsRecordsData recordsData;

    /**
     * Returns the INSTANCE of the ClaimsProcessor
     * 
     * @return INSTANCE of ClaimsProcessor
     */
    public static ClaimsProcessor getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ClaimsProcessor();
        }
        return INSTANCE;
    }

    /**
     * Private constructor. Restrict object creation from outside
     */
    private ClaimsProcessor() {
        recordsData = new ClaimsRecordsData();
    }

    /**
     * Process the records.
     */
    public void processRecords() {
        ClaimsRecordIterator claimsRecord = new ClaimsRecordIterator();
        Iterator<ClaimsRecord> iter = claimsRecord.iterator();
        int i=0;
        while (iter.hasNext()) {
            // ClaimsRecord record = iter.next();
            recordsData.addRecord(iter.next());
            i++;
            if(i%1000 == 0) {
                System.out.println(i);
            }
        }

        // System.out.println(recordsData.getCategoryDistributions());
        // System.out.println(recordsData.getPersonCategoryMap());
        try {
            FileWriter writer = new FileWriter("Output_Old.txt");
            BufferedWriter bw = new BufferedWriter(writer);
            bw.write(PersonCounts.getOutputFormatHeader() + "\n");
            for (Entry<String, PersonCounts> entry : recordsData
                    .getPersonData().entrySet()) {
                bw.write(entry.getValue().getOutputFormat(IndexAlgorithm.OLD) + "\n");
                //System.out.println(entry.getValue().getOutputFormat());
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ClaimsProcessor instance = ClaimsProcessor.getInstance();
        instance.processRecords();
    }
}
